"""
try:
    x = int(input("请输入一个整数: "))
    y = 10 / x
    print("结果:", y)
except ValueError:
    print("输入的不是有效整数！")
except ZeroDivisionError:
    print("不能除以零！")
"""

exceptions = [
    ("10 / 0", ZeroDivisionError),
    ("int('abc')", ValueError),
    ("'2' + 2", TypeError),
    ("[1, 2, 3][10]", IndexError),
    ("{'a': 1}['b']", KeyError),
    ("'hello'.nonexistent_method()", AttributeError),
    ("print(undefined_variable)", NameError),
    ("open('nonexistent_file.txt')", FileNotFoundError),
]

for code, expected_exception in exceptions:
    try:
        exec(code)
    except expected_exception as e:
        print(f"{code:30} -> {type(e).__name__}: {e}")


def process_data(data):
    try:
        number = int(data)
        result = 100 / number
        return result
    except ValueError:
        print("数据格式错误，记录日志...")
        raise  # 重新抛出原始异常
    except ZeroDivisionError:
        print("除零错误，记录日志...")
        raise  # 重新抛出原始异常


try:
    process_data("abc")
except Exception as e:
    print(f"外层捕获: {e}")


def process_file(filename):
    try:
        with open(filename) as f:
            return f.read()
    except FileNotFoundError as e:
        # 封装为业务相关异常，链接原始异常
        raise RuntimeError("文件处理失败") from e


try:
    data = process_file("not_exist.txt")
except RuntimeError as err:
    print("捕获到业务异常:", err)
    print("原始异常为:", err.__cause__)


class DataFormatError(Exception):
    def __init__(self, field, message):
        self.field = field
        self.message = message
        super().__init__(f"{field} 格式错误: {message}")


# 使用示例
try:
    raise DataFormatError("email", "缺少@符号")
except DataFormatError as e:
    print("捕获到自定义异常:", e)
    print(f"字段: {e.field}, 错误: {e.message}")


class FileOpener:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        print("文件已打开")
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
            print("文件已关闭")
        if exc_type:  # 发生了异常
            print("处理异常...", exc_tb)
            print(f"发生异常：{exc_type.__name__}: {exc_val}")
        return False  # 返回False，异常不会被吞掉


try:
    with FileOpener("demo.txt", "w") as f:
        f.write("hello world\n")
        raise ValueError("人为制造错误测试异常处理")
        f.write("这句话不会执行")
except Exception as e:
    print("外部捕获到异常:", e)

import logging

# 配置日志模块
logging.basicConfig(level=logging.ERROR)


class DatabaseError(Exception):
    pass


class ValidationError(Exception):
    pass


def get_user_from_db(user_id):
    """根据用户ID从数据库获取用户信息"""
    if user_id == 0:
        raise DatabaseError("数据库连接失败")
    return {"user_id": user_id, "name": "Test User", "age": 25}


def validate_and_process(user_data):
    """验证用户数据的有效性"""
    if not user_data.get("name") or user_data.get("age") < 0:
        raise ValidationError("用户信息无效")
    user_data["processed"] = True
    return user_data


def process_user_data(user_id):
    """综合处理用户数据"""
    try:
        user_data = get_user_from_db(user_id)
        result = validate_and_process(user_data)
        return result
    except DatabaseError as e:
        logging.error(f"数据库错误 - 用户ID: {user_id}, 错误: {e}")
        raise
    except ValidationError as e:
        logging.warning(f"数据验证失败 - 用户ID: {user_id}, 错误: {e}")
        return None
    except Exception as e:
        logging.critical(f"未知错误 - 用户ID: {user_id}, 错误: {e}")
        raise


process_user_data(1)
